package io.sdl.common.sys.service.impl;

import cn.hutool.core.date.DateTime;
import io.sdl.common.service.impl.CrudServiceImpl;
import io.sdl.common.sys.dao.SdlMessageReadStatusDao;
import io.sdl.common.sys.dto.SdlMessageReadStatusDTO;
import io.sdl.common.sys.entity.SdlMessageReadStatusEntity;
import io.sdl.common.sys.service.SdlMessageReadStatusService;
import io.sdl.common.utils.ConvertUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;




@Service("sdlMessageReadStatusService")
public class SdlMessageReadStatusServiceImpl extends CrudServiceImpl<SdlMessageReadStatusDao, SdlMessageReadStatusEntity, SdlMessageReadStatusDTO> implements SdlMessageReadStatusService {


    @Override
    public QueryWrapper<SdlMessageReadStatusEntity> getWrapper(Map params) {
        return null;
    }
    /*
     *插入新的未读记录
     * messageId 消息/评论ID
     * messageType 消息类型: 1-评论 2-聊天消
     * receiverId 接收者用户ID
     */
    @Override
    public void addUnreadRecord(Long messageId, Integer messageType, Long receiverId) {
        SdlMessageReadStatusEntity sdlMessageReadStatusEntity = baseDao.existsByMessageIdAndMessageTypeAndReceiverId(messageId, messageType, receiverId);
        if (sdlMessageReadStatusEntity ==null) {
            SdlMessageReadStatusEntity status = new SdlMessageReadStatusEntity();
            status.setMessageId(messageId);
            status.setMessageType(messageType);
            status.setReceiverId(receiverId);
            status.setCreatedAt(DateTime.now());
            baseDao.insert(status);
        }
    }


    /*
     * 标记消息为已读
     * messageId 消息/评论ID
     * messageType 消息类型: 1-评论 2-聊天消
     * receiverId 接收者用户ID
     */
    @Override
    public void markAsRead(Long messageId, Integer messageType, Long receiverId) {

        SdlMessageReadStatusEntity status = baseDao.findByMessageIdAndMessageTypeAndReceiverId(messageId, messageType, receiverId);

        if (status != null) {
            status.setIsRead(1);
            status.setReadTime(DateTime.now());
            baseDao.updateById(status);

        }
    }

    /*
     * 获取未读消息数量
     * messageType 消息/评论ID
     * receiverId 接收者用户ID
     */
    @Override
    public Integer getUnreadCount(Integer messageType, Long receiverId) {
        return baseDao.countByMessageTypeAndReceiverIdAndIsRead(messageType,receiverId,0);
    }


    /*
     * 获取未读消息列表
     * messageType 消息/评论ID
     * receiverId 接收者用户ID
     */
    @Override
    public List<SdlMessageReadStatusDTO> getUnreadMessageIds(Integer messageType, Long receiverId) {
        return ConvertUtils.sourceToTarget(baseDao.findMessageIdsByMessageTypeAndReceiverIdAndIsRead(messageType, receiverId, 0),SdlMessageReadStatusDTO.class);
    }
}